import type { ComponentInfo, ComponentProp, ComponentExample } from '../types/index.js';
import { RepositoryFactory } from '../database/repositories/index.js';
import { CacheManager } from '../cache/index.js';
import type { ComponentAttributes, ComponentCreationAttributes } from '../database/models/index.js';

/**
 * 数据库版本的组件注册表
 * 提供与原有 ComponentRegistry 相同的接口，但使用数据库存储
 */
export class DatabaseComponentRegistry {
  private repositories: RepositoryFactory;
  private cacheManager?: CacheManager;
  private initialized = false;

  constructor(repositories: RepositoryFactory, cacheManager?: CacheManager) {
    this.repositories = repositories;
    this.cacheManager = cacheManager;
  }

  /**
   * 初始化组件注册表
   */
  async initialize(): Promise<void> {
    if (this.initialized) return;
    
    try {
      // 检查数据库连接
      const health = await this.repositories.checkHealth();
      if (health.status !== 'healthy') {
        throw new Error('Database connection is not healthy');
      }
      
      this.initialized = true;
      console.log('✅ DatabaseComponentRegistry 初始化完成');
    } catch (error) {
      console.error('❌ DatabaseComponentRegistry 初始化失败:', error);
      throw error;
    }
  }

  /**
   * 注册组件 - 转换为数据库格式并存储
   */
  async registerComponent(component: ComponentInfo): Promise<void> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      const componentRepo = this.repositories.getComponentRepository();
      
      // 转换为数据库格式
      const componentData = this.convertToDbFormat(component);
      
      // 创建组件及其关联数据
      const savedComponent = await componentRepo.createWithRelations(componentData);
      
      // 清除相关缓存
      if (this.cacheManager) {
        await this.clearComponentCache(component.name, component.category);
      }
      
      console.log(`✅ 组件 ${component.name} 注册成功`);
    } catch (error) {
      console.error(`❌ 组件 ${component.name} 注册失败:`, error);
      throw error;
    }
  }

  /**
   * 获取单个组件
   */
  async getComponent(name: string): Promise<ComponentInfo | undefined> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      // 尝试从缓存获取
      const cacheKey = `component:${name}`;
      if (this.cacheManager) {
        const cached = await this.cacheManager.get<ComponentInfo>(cacheKey, 'component');
        if (cached) {
          return cached;
        }
      }

      const componentRepo = this.repositories.getComponentRepository();
      const dbComponent = await componentRepo.findByName(name);
      
      if (!dbComponent) {
        return undefined;
      }

      // 转换为前端格式
      const component = this.convertFromDbFormat(dbComponent);
      
      // 缓存结果
      if (this.cacheManager) {
        await this.cacheManager.set(cacheKey, component, 'component');
      }
      
      // 更新访问热度
      await componentRepo.updatePopularityScore(dbComponent.id, 1);
      
      return component;
    } catch (error) {
      console.error(`❌ 获取组件 ${name} 失败:`, error);
      return undefined;
    }
  }

  /**
   * 获取所有组件
   */
  async getAllComponents(): Promise<ComponentInfo[]> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      // 尝试从缓存获取
      const cacheKey = 'components:all';
      if (this.cacheManager) {
        const cached = await this.cacheManager.get<ComponentInfo[]>(cacheKey, 'component');
        if (cached) {
          return cached;
        }
      }

      const componentRepo = this.repositories.getComponentRepository();
      const { ComponentProp, ComponentExample, ComponentImport } = await import('../database/models/index.js');
      
      const dbComponents = await componentRepo.findAll({
        include: [
          { model: ComponentProp, as: 'props' },
          { model: ComponentExample, as: 'examples' },
          { model: ComponentImport, as: 'imports' },
        ],
        order: [['popularity_score', 'DESC']],
      });

      // 转换为前端格式
      const components = dbComponents.map(comp => this.convertFromDbFormat(comp));
      
      // 缓存结果
      if (this.cacheManager) {
        await this.cacheManager.set(cacheKey, components, 'component');
      }
      
      return components;
    } catch (error) {
      console.error('❌ 获取所有组件失败:', error);
      return [];
    }
  }

  /**
   * 搜索组件
   */
  async searchComponents(query: string, category?: string, limit = 10): Promise<ComponentInfo[]> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      // 生成缓存键
      const cacheKey = `search:${query}:${category || 'all'}:${limit}`;
      
      // 尝试从缓存获取
      if (this.cacheManager) {
        const cached = await this.cacheManager.get<ComponentInfo[]>(cacheKey, 'search');
        if (cached) {
          return cached;
        }
      }

      const componentRepo = this.repositories.getComponentRepository();
      const searchResult = await componentRepo.searchComponents(query, {
        category,
        limit,
        offset: 0,
      });

      // 转换为前端格式
      const components = searchResult.rows.map(comp => this.convertFromDbFormat(comp));
      
      // 缓存搜索结果
      if (this.cacheManager) {
        await this.cacheManager.set(cacheKey, components, 'search');
      }
      
      return components;
    } catch (error) {
      console.error(`❌ 搜索组件失败 [${query}]:`, error);
      return [];
    }
  }

  /**
   * 根据分类获取组件
   */
  async getComponentsByCategory(category: string): Promise<ComponentInfo[]> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      // 尝试从缓存获取
      const cacheKey = `category:${category}`;
      if (this.cacheManager) {
        const cached = await this.cacheManager.get<ComponentInfo[]>(cacheKey, 'component');
        if (cached) {
          return cached;
        }
      }

      const componentRepo = this.repositories.getComponentRepository();
      const searchResult = await componentRepo.findByCategory(category);

      // 转换为前端格式
      const components = searchResult.rows.map(comp => this.convertFromDbFormat(comp));
      
      // 缓存结果
      if (this.cacheManager) {
        await this.cacheManager.set(cacheKey, components, 'component');
      }
      
      return components;
    } catch (error) {
      console.error(`❌ 获取分类组件失败 [${category}]:`, error);
      return [];
    }
  }

  /**
   * 获取热门组件
   */
  async getPopularComponents(limit: number = 10): Promise<ComponentInfo[]> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      const componentRepo = this.repositories.getComponentRepository();
      const dbComponents = await componentRepo.getPopularComponents(limit);

      return dbComponents.map(comp => this.convertFromDbFormat(comp));
    } catch (error) {
      console.error('❌ 获取热门组件失败:', error);
      return [];
    }
  }

  /**
   * 获取所有分类
   */
  async getCategories(): Promise<string[]> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      const componentRepo = this.repositories.getComponentRepository();
      return await componentRepo.getCategories();
    } catch (error) {
      console.error('❌ 获取分类列表失败:', error);
      return [];
    }
  }

  /**
   * 转换 ComponentInfo 到数据库格式
   */
  private convertToDbFormat(component: ComponentInfo): {
    component: ComponentCreationAttributes;
    props?: Array<any>;
    examples?: Array<any>;
    imports?: Array<any>;
  } {
    return {
      component: {
        name: component.name,
        category: component.category,
        description: component.description,
        version: component.version || '5.0',
        framework: 'react' as const,
        popularity_score: 0,
        search_keywords: this.generateSearchKeywords(component),
      },
      props: component.props?.map(prop => ({
        name: prop.name,
        type: prop.type,
        required: prop.required,
        description: prop.description,
        default_value: prop.defaultValue ? String(prop.defaultValue) : undefined,
        options: prop.options || null,
      })),
      examples: component.examples?.map(example => ({
        title: example.title,
        description: example.description,
        code: example.code,
        framework: 'react' as const,
      })),
      imports: component.imports?.map(importStmt => ({
        import_statement: importStmt,
        framework: 'react' as const,
      })),
    };
  }

  /**
   * 从数据库格式转换为 ComponentInfo
   */
  private convertFromDbFormat(dbComponent: any): ComponentInfo {
    return {
      name: dbComponent.name,
      category: dbComponent.category,
      description: dbComponent.description || '',
      version: dbComponent.version,
      props: dbComponent.props?.map((prop: any) => ({
        name: prop.name,
        type: prop.type,
        required: prop.required,
        description: prop.description || '',
        defaultValue: prop.default_value,
        options: prop.options,
      })) || [],
      examples: dbComponent.examples?.map((example: any) => ({
        title: example.title,
        description: example.description || '',
        code: example.code,
        preview: example.preview_url,
      })) || [],
      imports: dbComponent.imports?.map((imp: any) => imp.import_statement) || [],
      dependencies: dbComponent.dependencies || [],
    };
  }

  /**
   * 生成搜索关键词
   */
  private generateSearchKeywords(component: ComponentInfo): string {
    const keywords = [
      component.name.toLowerCase(),
      component.description.toLowerCase(),
      component.category,
      ...(component.props?.map(prop => prop.name) || []),
    ];
    
    return keywords.join(',');
  }

  /**
   * 清除组件相关缓存
   */
  private async clearComponentCache(componentName: string, category: string): Promise<void> {
    if (!this.cacheManager) return;

    try {
      await Promise.all([
        this.cacheManager.delete(`component:${componentName}`),
        this.cacheManager.delete(`category:${category}`),
        this.cacheManager.delete('components:all'),
        // 清除搜索缓存（使用模式匹配）
        this.cacheManager.clear('search'),
      ]);
    } catch (error) {
      console.warn('⚠️  清除缓存失败:', error);
    }
  }

  /**
   * 清除所有缓存
   */
  async clearAllCache(): Promise<void> {
    if (!this.cacheManager) return;

    try {
      await this.cacheManager.clear('component');
      await this.cacheManager.clear('search');
      console.log('✅ 组件缓存已清除');
    } catch (error) {
      console.error('❌ 清除缓存失败:', error);
    }
  }

  /**
   * 获取统计信息
   */
  async getStats(): Promise<{
    totalComponents: number;
    categoryCounts: Array<{ category: string; count: number }>;
    popularComponents: ComponentInfo[];
  }> {
    try {
      if (!this.initialized) {
        await this.initialize();
      }

      const componentRepo = this.repositories.getComponentRepository();
      
      const [
        totalComponents,
        categoryCounts,
        popularComponents,
      ] = await Promise.all([
        componentRepo.count(),
        componentRepo.getComponentCountByCategory(),
        this.getPopularComponents(5),
      ]);

      return {
        totalComponents,
        categoryCounts,
        popularComponents,
      };
    } catch (error) {
      console.error('❌ 获取统计信息失败:', error);
      return {
        totalComponents: 0,
        categoryCounts: [],
        popularComponents: [],
      };
    }
  }
}